using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;
using ShopPowerTemplate.Entities;
using System.Linq.Expressions;
using System.Threading.Tasks;
using ShopPowerTemplate.Services;
using System.IO;
using ShopPowerTemplate.WcfService.Properties;

namespace ShopPowerTemplate.WcfService
{
    public partial class RestService : IRestService
    {
        public Stream PaymentPending(int orderId)
        {
            IOrderService serviceOrder = IoC.IoCFactory.Resolve<IOrderService>();
            Order order = serviceOrder.Find(orderId);

            if (order != null && order.OrderState.Id == (int)OrderStateEnum.NuevoPedido)
            {
                IOrderStateService serviceOrderState = IoC.IoCFactory.Resolve<IOrderStateService>();
                order.OrderState = serviceOrderState.Find((int)OrderStateEnum.PendienteDePago);

                serviceOrder.Change(order);
            }

            return GetPage(Resources.Success);
        }

        public Stream PaymentCanceled(int orderId)
        {
            IOrderService serviceOrder = IoC.IoCFactory.Resolve<IOrderService>();
            Order order = serviceOrder.Find(orderId);

            if (order != null && order.OrderState.Id == (int)OrderStateEnum.NuevoPedido)
            {
                IOrderStateService serviceOrderState = IoC.IoCFactory.Resolve<IOrderStateService>();
                order.OrderState = serviceOrderState.Find((int)OrderStateEnum.Cancelado);

                serviceOrder.Change(order);
            } 
            
            return GetPage(Resources.Cancel);
        }

        private Stream GetPage(string page)
        {
            // Get site relative base url for use in javascript ajax requests
            var baseUrl = WebOperationContext.Current.IncomingRequest.UriTemplateMatch.BaseUri.AbsolutePath;
            page = page.Replace("%BaseURL%", baseUrl);

            MemoryStream stream = new MemoryStream(Encoding.UTF8.GetBytes(page));

            WebOperationContext.Current.OutgoingResponse.ContentType = "text/html";
            return stream;
        }
    }
}

